//判断用户是否登录
let username = getCookie('username');
let firUl = document.querySelector('.firUl');
let login = document.querySelector('.login');
let reg = document.querySelector('.register');
let empty = document.querySelector('.empty')
//console.log(reg)
if (username) {//用户名存在
    firUl.innerHTML = `<li class="login">
    <a href="javascript:;">${username}</a>
</li>
<li>|</li>
<li class='register'>
    <a href="javascript:;">退出</a>
</li>`
    //用户点击退出
    document.querySelector('.register').onclick = function () {
        //console.log(123)
        layer.confirm('您确定要退出吗？', { btn: ['确定', '取消'] }, function () {//点击确定
            delCookie('username');
            firUl.innerHTML = `<li class="login">
    <a href="javascript:;">登录</a>
</li>
<li>|</li>
<li class='register'>
    <a href="javascript:;">注册</a>
</li>`
            layer.msg('退出成功', { icon: 1, time: 500 })
            location.reload();
        },
            //点击取消的按钮，就是不退出
            function () {
                layer.msg('已取消', { icon: 1, time: 500 })
                return false;
            })
    }
}
//快来选购吧
$('.selectGoods').click(function(){
    location.href = '../html/xiaomi.html'
})
//根据地址后面携带的参数来判断是否加入购物车
var params = (function () {
    var search = location.search;//获取location的search属性，保存在search中
    var params = {}; //创建空对象params
    if (search != "") {        //如果search不是空字符串
        search.slice(1).split("&").forEach(    //?username=zhangdong&pwd=123456;//search去开头?，按&切割为数组，forEach
            function (val) {
                var arr = val.split("=");        //将当前元素值按=切割，保存在arr中
                params[arr[0]] = arr[1];        //向params中添加一个元素,属性名为arr[0],值为arr[1]
            }
        );
    }
    return params; //返回param
})();
//
let cart = document.querySelector('#cart');
let payCart = document.querySelector('#payCart');
let str = '';
for(let i =0;i<JSON.parse(localStorage.getItem('data')).length;i++){
if (getCookie('username') == JSON.parse(localStorage.getItem('data'))[i]['username'] && JSON.parse(localStorage.getItem('data'))[i].length !=0) {
    empty.style.display = 'none'
    cart.style.display = 'block'
    payCart.style.display = 'block'
}
else {
    empty.style.display = 'block'
    cart.style.display = 'none'
    payCart.style.display = 'none'
}
}
for (let i = 0; i < JSON.parse(localStorage.getItem('data')).length; i++) {
    if (JSON.parse(localStorage.getItem('data'))[i]['username'] == getCookie('username')) {
        //加入了购物车
        // empty.style.display = 'none'
        // cart.style.display = 'block'
        // payCart.style.display = 'block'
        for (let j = 0; j < JSON.parse(localStorage.getItem('pros')).length; j++) {
            if (JSON.parse(localStorage.getItem('data'))[i]['goodsId'] == JSON.parse(localStorage.getItem('pros'))[j]['id']) {
                str = `  
                <ol class="firOl">
                    <li><input type="checkbox" class='check checkSingle'>&nbsp;&nbsp;&nbsp;选择</li>
                    <li style='font-size:12px;overflow:hidden;text-align:start;'><img src="${JSON.parse(localStorage.getItem('pros'))[j]['urlImg']}" alt="" style="width:50px;height:50px;vertical-align:middle;">${JSON.parse(localStorage.getItem('pros'))[j]['goods']}</li>
                    <li>${JSON.parse(localStorage.getItem('pros'))[j]['price']}</li>
                    <li><div data-id="${JSON.parse(localStorage.getItem('data'))[i]['goodsId']}"><span style="display:inline-block;width:40px;height:40px;" class='reduce'>-</span><span style="display:inline-block;width:40px;height:40px;" class='numGoods'>${JSON.parse(localStorage.getItem('data'))[i]['value']}
                    </span><span style="display:inline-block;width:40px;height:40px" class='add'>+</span></div></li>
                    <li class='subtotal' data-id="${JSON.parse(localStorage.getItem('data'))[i]['value'] * JSON.parse(localStorage.getItem('pros'))[j]['price']}.00">${JSON.parse(localStorage.getItem('data'))[i]['value'] * JSON.parse(localStorage.getItem('pros'))[j]['price']}.00</li>
                    <li><i class=' iconfont icon-shanchu del'><i></li></ol>`

                document.querySelector('.pros').innerHTML += str;
                $('.pros').prepend($('.firOl').last())
                selectAll();
                single();
                total();
                AddReduce();
            }
        }
    }
    // else{
    //         empty.style.display = 'block'
    //         cart.style.display = 'none'
    //         payCart.style.display = 'none'
    //         }

}
//绑定删除事件
$('.del').on('click', function () {//当用户点击删除的时候，相应的要将本地数据删除
    layer.confirm('确定移除所选商品吗？', ['确定', '取消'], () => {
        for (let i = 0; i < JSON.parse(localStorage.getItem('data')).length; i++) {
            var arr = JSON.parse(localStorage.getItem('data'));
            for (let j = 0; j < JSON.parse(localStorage.getItem('pros')).length; j++) {
                if (JSON.parse(localStorage.getItem('pros'))[j]['id'] === JSON.parse(localStorage.getItem('data'))[i]['goodsId'] && JSON.parse(localStorage.getItem('pros'))[j]['urlImg'] == $(this).parent().siblings().eq(1).find('img').attr('src')) {
                    arr.splice(i, 1)
                    $(this).parent().parent().remove();
                }
            }
            total();
            localStorage.setItem('data', JSON.stringify(arr));
            layer.msg('移除成功', { icon: 1, time: 500 })
        }
        location.reload();
    }, function () {
        // 点击取消
        layer.msg('已取消', { time: 1000 });
    })
})


// //封装已选择的数量
// let data_select = document.querySelector('.data_select');
// let selects = 0;
// function selected(){
//     //判断点击的是当前商品
//     // if(){

//     // }
//     for(let i =0;i<JSON.parse(localStorage.getItem('data')).length;i++){
//         selects = Number(JSON.parse(localStorage.getItem('data'))[i]['value'])            
//     }
//     data_select.innerHTML=Number(data_select.innerHTML)+selects;
// }
//全选和单选
let checkAll = document.querySelector('.checkAll');
let checkSingle = document.querySelectorAll('.checkSingle');
let check = document.querySelectorAll('.check');
//绑定全选事件
function selectAll() {
    $('.checkAll').click(function () {
        $('.checkAll').prop('checked', $(this).prop('checked'));
        $('.checkSingle').prop('checked', $(this).prop('checked'));
        total();
    })
}
//绑定单选事件
function single() {
    $('.checkSingle').click(function () {
        //将jq转成数组，也就是伪数组转为数组
        let singles = Array.prototype.slice.call($('.checkSingle'));
        let flag = singles.every(v => $(v).prop('checked'));
        $('.checkAll').prop('checked', flag);
        total();
    })
}
//商品合计的总价格,应该是用户选中的商品的价格和
//封装价格

function total() {
    let totalPrice = 0;
    let totalSum = 0;
    let totalall = 0;
    let subtotal = 0;
    $('.checkSingle').each((i, v) => {
        // 判断是否勾选上
        if ($(v).prop('checked')) {
            //已选商品总数
            totalSum += $(v).parent().siblings().eq(2).find('div').find('.numGoods').text() - 0;
            //已选总价格
            totalPrice += Number($(v).parent().siblings().eq(3).text());
            //小计
        }
        //商品总数
        else {
            totalall += $(v).parent().siblings().eq(2).find('div').find('.numGoods').text() - 0;
        }
    })
    $('.data_sum').text(totalSum + totalall);
    $('.data_select').text(totalSum);
    $('.data_totalsum').text(totalPrice);
    //$('.subtotal').text(subtotal)
}
//封装加减绑定事件函数
function AddReduce() {
    let subtotal = 0;
    //当用户点击了加商品，那么对应的数量、价格以及本地存储数据均需要改变
    $('.add').click(function () {
        $('.reduce').prop('disabled', false);
        //拿到当前的数量
        let num = $(this).prev().text() - 0;
        //加1
        $(this).prev().text(++num);
        //小计
        $(this).parent().parent().siblings().eq(3).text(($(this).prev().text()) * ($(this).parent().parent().siblings().eq(2).text()) + '.00')
        //修改本地数据
        let goodsId = $(this).parent()[0].dataset.id;
        //console.log(goodsId)
        let data = JSON.parse(localStorage.getItem('data'));
        let cartGoods = data.find(v => v.username === username && v.goodsId === goodsId);
        cartGoods.value = num;
        // 将修改后的data写入本地购物车
        localStorage.setItem('data', JSON.stringify(data))
        total();
        //$('.data_sum').text(totalSum+totalall+num);
        //totalPrice += $(v).parent().siblings().eq(3).text() - 0;

    })
    // 减绑定点击事件
    $('.reduce').click(function () {
        $('.add').prop('disabled', false);
        let num = $(this).next().text() - 0;
        if (num <= 1) {
            $(this).next().text(1);
            layer.msg('不能再少了哦');
            $(this).prop('disabled', true);
        } else {
            $(this).next().text(--num);
        }
        //小计
        $(this).parent().parent().siblings().eq(3).text(($(this).next().text()) * ($(this).parent().parent().siblings().eq(2).text()) + '.00')
        // 修改本地购物车中的数量
        let goodsId = $(this).parent()[0].dataset.id;
        let data = JSON.parse(localStorage.getItem('data'));
        let cartGoods = data.find(v => v.username === username && v.goodsId === goodsId);
        cartGoods.value = num;
        // 将修改后的data写入本地
        localStorage.setItem('data', JSON.stringify(data))
        total();
        //$('.data_sum').text(totalSum+totalall+num);
        //totalPrice += $(v).parent().siblings().eq(3).text() - 0;

    })
}
//点击继续购物将选购的商品总数通过地址传到首页购物车进行显示
let goShop = document.querySelector('.go_shopping');
let data_sum = document.querySelector('.data_sum')

//console.log(cartSum)
goShop.onclick = function () {
    let cartSum = data_sum.innerText;
    setTimeout(function () {
        location.href = `../html/xiaomi.html?sum=${cartSum} `
    }, 500)

}
//点击去下单
$('.toPay').click(function () {
    layer.confirm('确定支付吗？', { btn: ['确定', '取消'] },
        //点击弹出的确定按钮，应该删除勾选的商品
         function (){
             //当没选商品时
            if($('.check').prop('checked')==false){
                layer.msg('还未勾选商品哟', { icon: 0, time: 500 ,shade:[0.8, '#393D49']})
             }
             //全选
            if($('.checkAll').prop('checked')==true){
                localStorage.removeItem('data');
                layer.msg('支付成功!', { icon: 1, time: 500 })
                //location.reload();
                //跳转支付成功的页面
                location.href = '../html/success.html'
            }
            //单选
            $('.checkSingle').each((i, v) => {
                var arr = JSON.parse(localStorage.getItem('data'));
                // 判断是否勾选上
                if ($(v).prop('checked')) {
                    for (let i = 0; i < JSON.parse(localStorage.getItem('data')).length; i++) {
                        var arr = JSON.parse(localStorage.getItem('data'));
                        for (let j = 0; j < JSON.parse(localStorage.getItem('pros')).length; j++) {
                            if (JSON.parse(localStorage.getItem('pros'))[j]['id'] === JSON.parse(localStorage.getItem('data'))[i]['goodsId'] && JSON.parse(localStorage.getItem('pros'))[j]['urlImg'] == $(v).parent().siblings().eq(0).find('img').attr('src')) {
                                arr.splice(i, 1)
                                $(v).parent().parent().remove();
                            }
                        }
                        total();
                        localStorage.setItem('data', JSON.stringify(arr));
                        layer.msg('支付成功!', { icon: 1, time: 500 })
                        location.href = '../html/success.html'
                    }
                }
            })
           
        },
        //点击取消的按钮，就是不支付
         ()=>{
            layer.msg('已取消', { icon: 1, time: 500 })
            return false;
        })
})

